package com.example.adnroidstyle;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

	private static String SMS_CONTENT = "content://sms";

	private EditText mEditTextPhone;
	private EditText mEditTextVerifacationCode;
	SmsContent mSmsContent;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mEditTextPhone = (EditText) findViewById(R.id.edittext_phone);
		mEditTextVerifacationCode = (EditText) findViewById(R.id.edittext_verifaction);

		mSmsContent = new SmsContent(new Handler());
		ContentResolver resolver = getContentResolver();
		resolver.registerContentObserver(Uri.parse(SMS_CONTENT), true, mSmsContent);

	}

	@Override
	protected void onStart() {
		super.onStart();

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (mSmsContent != null) {
			getContentResolver().unregisterContentObserver(mSmsContent);
			mSmsContent = null;
		}

	}


	class SmsContent extends ContentObserver {
		private Cursor mCursor = null;
		public SmsContent(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			mCursor = managedQuery(Uri.parse("content://sms/inbos"),
					new String[]{"_id", "address", "read", "body"},
					"address=? and read=?", new String[]{"监听的号码", "13681960838"},
					"_id desc" );

			// 按id排序，如果按date排序的话，修改手机时间后，读取的短信就不准了
			if (mCursor != null && mCursor.getCount() > 0) {
				ContentValues contentValues = new ContentValues();
				contentValues.put("read", "1");	//修改短信为已读模式
				mCursor.moveToNext();
				int smsbodyColumnIndex = mCursor.getColumnIndex("body");
				String smsBody = mCursor.getString(smsbodyColumnIndex);
				mEditTextVerifacationCode.setText(getDynaicPassword(smsBody));

			}

			// 在用4.0以上系统中用managedQuery的时候，不能主动调用close()方法，否则会崩溃
			if (Build.VERSION.SDK_INT < 14) {
				mCursor.close();
			}
		}

	}

	public static String getDynaicPassword(String str) {
		Pattern continuousNumberPattern = Pattern.compile("[0-9\\.]+");
		Matcher matcher = continuousNumberPattern.matcher(str);
		String dynamicPassword = "";
		while (matcher.find()) {
			if(matcher.group().length() == 6) {
				Log.e("DynamicPsd", matcher.group());
				dynamicPassword = matcher.group();
			}
		}

		return dynamicPassword;
	}

}
